package com.lzx.iteam;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.*;
import android.os.Process;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.*;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.lzx.iteam.R;
import com.lzx.iteam.skin.UnZip;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SkinList extends Activity{

//    MIUI "/data/sdcard/"
    
    final int DOWNLOAD_BEGIN = 0;
    final int DOWNLOAD_OK = 1;
    final int DOWNLOAD_PROGRESS = 2;
    final int DOWNLOAD_FAILED = 3;
    HttpURLConnection conn;
    ExecutorService es;
    int progress;
    int max;
    String name;
    File des;
    WebView wv;
    LinearLayout container;
    Context context;
    ProgressDialog pd;
    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch(msg.what){
                case DOWNLOAD_BEGIN:
                    pd.setTitle(name+"正在下载");
                    pd.setMax(max);
                    pd.setProgress(0);
                    if(!pd.isShowing()){
                        pd.show();
                    }
                    pd.setCancelable(false);
                    break;
                case DOWNLOAD_PROGRESS:
                    if(pd!=null&&pd.isShowing()){
                        pd.setProgress(progress);
                    }
                    break;
                case DOWNLOAD_OK:
                    Toast.makeText(getApplicationContext(), "download complete", Toast.LENGTH_LONG).show();
                    UnZip zip = new UnZip(SkinList.this);
                    File file = getApplicationContext().getFilesDir();
                    String sdpath = null;
                    if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                        if ("MIONE".equals(Build.BOARD)) {// other miui path?
                            sdpath = "/data/sdcard";
                        } else {
                            Toast.makeText(getApplicationContext(), "NO SDCard", Toast.LENGTH_LONG).show();
                            if(pd.isShowing()){
                                pd.dismiss();
                            }
                            break;
                        }

                    } else {
                        try {
                            sdpath = Environment.getExternalStorageDirectory().getCanonicalPath();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "SD卡错误", Toast.LENGTH_LONG).show();
                            if(pd.isShowing()){
                                pd.dismiss();
                            }
                            break;
                        }
                    }
                    try {
                        zip.UnZipFolder(sdpath + "/clouddialerSkin/" + (String)msg.obj, file.getAbsolutePath()+ "/skin");
                    } catch (Exception e) {
                        Toast.makeText(SkinList.this, "皮肤安装失败!",Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                    if(pd!=null&&pd.isShowing()){
                        pd.dismiss();
                    }
                    max = 0;
                    progress = 0;
                    /*String filePath = null;
                      try {
                          filePath = des.getCanonicalPath();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                      if(filePath!=null){
                          IphoneDialogUtil.showCustomMessageOK(context, R.string.menu_done, R.string.download_skin_success, R.string.ok);
                          Intent i = new Intent(Intent.ACTION_VIEW);
                          i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                          i.setDataAndType(Uri.parse("file://" + filePath),"application/vnd.android.package-archive");  
                          getApplication().startActivity(i);  
                      }*/
                    break;
                    
                case DOWNLOAD_FAILED:
                    if(pd!=null&&pd.isShowing()){
                        pd.dismiss();
                    }
                    progress = 0;
                    max = 0;
                    Toast.makeText(context, "download failed", Toast.LENGTH_LONG).show();
                    break;
            }
        };  
      };
      
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_PROGRESS);

        setContentView(R.layout.skin_list);
        setTitle("皮肤超市");
        context = this;
        container = (LinearLayout) findViewById(R.id.skincontainer);
        es = Executors.newSingleThreadExecutor();
        wv = (WebView) findViewById(R.id.skin_list_wv);
        WebSettings ws = wv.getSettings(); 
        ws.setJavaScriptEnabled(true);
        ws.setAllowFileAccess(true);
        ws.setBuiltInZoomControls(true);
        ws.setSavePassword(false);
        wv.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view,final String url){ 
                if(url.contains("/themes/download")){
                        pd = new ProgressDialog(context,0);
                        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pd.setButton("取消", new DialogInterface.OnClickListener() {
                            
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                pd.cancel();
                                pd.dismiss();
                                if(conn != null){
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            conn.disconnect();
                                        }
                                    }).start();
                                }
                            }
                        });
                        
                        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if(conn != null){
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            conn.disconnect();
                                        }
                                    }).start();
                                }
                            }
                        });
                    if(!pd.isShowing()){
                        pd.show();
                    }

                    String sdpath = null;
                    if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                        if ("MIONE".equals(Build.BOARD)) {// other miui path?
                            sdpath = "/data/sdcard";
                        } else {
                            Toast.makeText(getApplicationContext(), "NO SDCard", Toast.LENGTH_LONG).show();
                            if(pd.isShowing()){
                                pd.dismiss();
                            }
                            return true;
                        }
                        
                    } else {
                        try {
                            sdpath = Environment.getExternalStorageDirectory().getCanonicalPath();
                        } catch (IOException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "SD卡错误", Toast.LENGTH_LONG).show();
                            if(pd.isShowing()){
                                pd.dismiss();
                            }
                            return true;
                        }
                    }
                    
                    final String path = sdpath;
                    es.execute(new Runnable() {
                        
                        @Override
                        public void run() {
                            try {
                                File dir = new File(path+"/clouddialerSkin");
                                if(!dir.exists()){
                                    dir.mkdir();
                                    dir.setExecutable(true, false);
                                    dir.setReadable(true, false);
                                }
                                des = new File(dir.getCanonicalPath()+"/"+name);
                                if(!des.exists()){
                                    des.createNewFile();
                                    des.setExecutable(true, false);
                                    des.setReadable(true, false);
                                }
                                String downLoad = url;
                                downLoad = url.replace("os=android", "os=ios");
                                URL apkurl = new URL(downLoad);
                                conn = (HttpURLConnection) apkurl.openConnection();
                                conn.connect();
                                if(conn.getResponseCode()!=HttpURLConnection.HTTP_OK){
                                    handler.sendEmptyMessage(DOWNLOAD_OK);
                                    return;
                                }
                                String contentDisposition = conn.getHeaderField("Content-Disposition");
                                if(contentDisposition != null){
                                    name = URLDecoder.decode(contentDisposition.substring(contentDisposition.lastIndexOf("=")+1), "UTF-8");
                                }else{
                                    name = "error";
                                }
                                max = conn.getContentLength();
                                handler.sendEmptyMessage(DOWNLOAD_BEGIN);

                                OutputStream os = new FileOutputStream(des);
                                InputStream is = conn.getInputStream();
                                byte[] bytes = new byte[1024];
                                int len = 0;
                                while((len=is.read(bytes))>0){
                                    os.write(bytes, 0, len);
                                    progress+=len;
                                    handler.sendEmptyMessage(DOWNLOAD_PROGRESS);
                                }
                                os.flush();
                                is.close();
                                os.close();
                                Message msg = new Message();
                                msg.what = DOWNLOAD_OK;
                                msg.obj = des.getName();
                                handler.sendMessage(msg);
                            } catch (UnsupportedEncodingException e) {
                                downloadFailed();
                            } catch (MalformedURLException e) {
                                downloadFailed();
                            } catch (FileNotFoundException e) {
                                downloadFailed();
                            } catch (IOException e) {
                                downloadFailed();
                            }
                        }
                    });
                }else if(url.contains("tj://")){
                    String u = url.replace("tj://", "http://");
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(u));
                    startActivity(intent);
                }
                else{
                    view.loadUrl(url);
                }
                return true;
            }  
        }); 
        wv.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //IphoneDialogUtil.showCustomMessageOK(context, null, message, null);
                return super.onJsAlert(view, url, message, result);
            }
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                setProgress(newProgress*100);
            }
        });

        wv.loadUrl("http://tj.bohaojingling.com/themes/");
    }
    

    public void downloadFailed(){
        if(pd!=null&&pd.isShowing()){
            pd.dismiss();
        }
        handler.sendEmptyMessage(DOWNLOAD_FAILED);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK){
            this.finish();
/*
            overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
*/
        }
        return super.onKeyDown(keyCode, event);
    }
    
    
    @Override
    protected void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);
    }
    
    @Override
    protected void onDestroy() {
        //unbindService(conn);
        super.onDestroy();
        Process.killProcess(Process.myPid());
    }
    
}
